// pages/cart/cart.js
import {
  getSetting,
  chooseAddress,
  openSetting
} from "../../utils/asyncWx"
Page({


  data: {
    address: {},
    cart: [],
    allChecked: false,
    totalPrice: 0,
    totalNum: 0
  },


  onShow() {
    //1:获取缓存中的收货地址信息;
    const address = wx.getStorageSync("address");
    //获取缓存中购物车 的数据;
    const cart = wx.getStorageSync("cart") || [];
    this.setData({
      address
    })
    //调用自定义的方法setcart去更新购物车的数据
    this.setCart(cart)
  },
  //获取收货地址
  async handleChooseAddress() {
    try {
      // 1 获取权限状态
      const res1 = await getSetting()

      //表示看看用户有没有获取收货地址的权限;
      const scopeAddress = res1.authSetting['scope.address']
      if (scopeAddress === false) {
        //打开权限设置的页面; ---让用户重新设置权限;
        await openSetting()
      }

      // 调用收货地址的api
      let address = await chooseAddress()
      console.log(address)
      address.all = address.provinceName + address.cityName + address.countyName + address.detailInfo;

      //存到缓存中
      wx.setStorageSync("address", address);

    } catch (error) {
      console.log('你干哈呢')
    }
  },
  // 商品的选中状态发生变化的时候;
  handeItemChange(e) {
    // 先去获取被修改的商品的id
    const goods_id = e.currentTarget.dataset.id;
    //获取购物车数组;
    let {
      cart
    } = this.data;
    // 找到对应被修改的商品的对象;
    let index = cart.findIndex(v => v.goods_id === goods_id);
    //选中状态取反
    cart[index].checked = !cart[index].checked;
    this.setCart(cart);
  },
  setCart(cart) {
    // 
    let allChecked = true;
    // 总价格和总数量;
    let totalPrice = 0;
    let totalNum = 0;
    cart.forEach(v => {
      if (v.checked) {
        totalPrice += v.num * v.goods_price;
        totalNum += v.num;
      } else {
        allChecked = false;
      }
    })

    allChecked = cart.length != 0 ? allChecked : false;

    this.setData({
      cart,
      totalPrice,
      totalNum,
      allChecked
    })
    wx.setStorageSync("cart", cart);
  }
})